import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:qilo/core/constants/app_colors.dart';
import 'package:qilo/core/constants/app_icons.dart';
import 'package:qilo/core/utils/app_utils.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import '../../../core/providers/global_state_coordinator.dart';

/// 设置页面
class SettingsPage extends StatefulWidget {
  const SettingsPage({super.key});

  @override
  State<SettingsPage> createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  bool _isLoading = false;

  ImageProvider _getImageProvider(String imagePath) {
    if (imagePath.startsWith('assets/')) {
      return AssetImage(imagePath);
    } else {
      return FileImage(File(imagePath));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/my-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios, color: Colors.white, size: 20.w),
            onPressed: () => Navigator.of(context).pop(),
          ),
          title: Text(
            'Settings',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              fontFamily: 'Poppins',
            ),
          ),
          centerTitle: true,
        ),
        body: Consumer<GlobalStateCoordinator>(
          builder: (context, coordinator, child) {
            final userInfo = coordinator.currentUser;
            if (userInfo == null) {
              return const Center(
                child: Text(
                  'User not logged in',
                  style: TextStyle(color: Colors.white),
                ),
              );
            }

            return SingleChildScrollView(
              padding: EdgeInsets.all(16.w),
              child: Column(
                children: [
                  SizedBox(height: 20.h),

                  _buildAvatarSection(userInfo.avatar),

                  SizedBox(height: 20.h),

                  _buildUserNameSection(),

                  SizedBox(height: 20.h),

                  _buildSystemSettingsSection(),

                  SizedBox(height: 40.h),

                  _buildLogoutButton(),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildAvatarSection(String currentAvatar) {
    return Column(
      children: [
        SizedBox(
          width: 246.w,
          height: 209.h,
          child: Stack(
            children: [
              Image.asset(
                "assets/images/setting-top.png",
                width: 246.w,
                height: 209.h,
                fit: BoxFit.cover,
              ),
              Column(
                children: [
                  SizedBox(height: 93.h),
                  Row(
                    children: [
                      SizedBox(width: 110.w),
                      Container(
                        width: 52.w,
                        height: 52.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          image:
                              currentAvatar.isNotEmpty
                                  ? DecorationImage(
                                    image: _getImageProvider(currentAvatar),
                                    fit: BoxFit.cover,
                                  )
                                  : null,
                          color:
                              currentAvatar.isEmpty ? Colors.grey[300] : null,
                        ),
                        child:
                            currentAvatar.isEmpty
                                ? Icon(
                                  Icons.person,
                                  size: 60.w,
                                  color: Colors.grey[600],
                                )
                                : null,
                      ),
                    ],
                  ),
                ],
              ),
              Positioned(
                right: 50.w,
                bottom: 20.h,
                child: GestureDetector(
                  onTap: _pickAvatar,
                  child: Container(
                    width: 36.w,
                    height: 36.w,
                    decoration: const BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white,
                    ),
                    child: Icon(
                      MyIcons.iconEdit,
                      size: 20.w,
                      color: Colors.grey[700],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildUserNameSection() {
    return Consumer<GlobalStateCoordinator>(
      builder: (context, coordinator, child) {
        final currentUsername = coordinator.currentUser?.userName ?? '';
        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            GestureDetector(
              onTap: _showEditUsernameDialog,
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                child: Text(
                  currentUsername.isEmpty ? 'Enter your name' : currentUsername,
                  style: TextStyle(
                    color:
                        currentUsername.isEmpty ? Colors.white : Colors.white,
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily: 'Poppins',
                    decoration: TextDecoration.underline,
                    decorationColor: Colors.white,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
            GestureDetector(
              onTap: _showEditUsernameDialog,
              child: Container(
                padding: EdgeInsets.only(
                  left: 8.w,
                  top: 8.h,
                  bottom: 8.h,
                  right: 8.w,
                ),
                child: Icon(MyIcons.iconEdit2, color: Colors.white, size: 20.w),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildSystemSettingsSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'System Settings',
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontWeight: FontWeight.w600,
            fontFamily: 'Poppins',
          ),
        ),
        SizedBox(height: 16.h),
        _buildSettingsItem('Privacy Policy', Icons.privacy_tip_outlined),
        SizedBox(height: 12.h),
        _buildSettingsItem('Terms Of service', Icons.description_outlined),
        SizedBox(height: 12.h),
        _buildSettingsItem(
          'Delete Account',
          Icons.delete_outline,
          isDestructive: true,
        ),
      ],
    );
  }

  /// 构建设置项
  Widget _buildSettingsItem(
    String title,
    IconData icon, {
    bool isDestructive = false,
  }) {
    return GestureDetector(
      onTap: () => _handleSettingsItemTap(title),
      child: Container(
        height: 44.h,
        padding: EdgeInsets.only(left: 10.w, right: 16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6.r),
        ),
        child: Row(
          children: [
            SizedBox(width: 16.w),
            Expanded(
              child: Text(
                title,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  fontFamily: 'Poppins',
                ),
              ),
            ),
            Icon(Icons.arrow_forward_ios, color: Colors.black, size: 16.w),
          ],
        ),
      ),
    );
  }

  Widget _buildLogoutButton() {
    return SizedBox(
      width: double.infinity,
      height: 50.h,
      child: ElevatedButton(
        onPressed: _logout,
        style: ElevatedButton.styleFrom(
          backgroundColor: AppColors.iconColor,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25.r),
          ),
          elevation: 0,
        ),
        child: Text(
          'Log Out',
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontWeight: FontWeight.w600,
            fontFamily: 'Poppins',
          ),
        ),
      ),
    );
  }

  Future<void> _pickAvatar() async {
    try {
      setState(() {
        _isLoading = true;
      });

      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          specialPickerType: SpecialPickerType.noPreview,
        ),
      );

      if (result != null && result.isNotEmpty) {
        final AssetEntity asset = result.first;
        final File? file = await asset.file;

        if (file != null) {
          final String localPath = await _saveImageToLocal(file);

          if (!mounted) return;

          final coordinator = Provider.of<GlobalStateCoordinator>(
            context,
            listen: false,
          );
          await coordinator.updateUserInfo(
            coordinator.currentUser?.userName ?? '',
            avatar: localPath,
          );

          if (mounted) {
            AppUtils.showSuccess(context, "Avatar updated successfully");
          }
        }
      }
    } catch (e) {
      if (mounted) {
        AppUtils.showError(context, "Failed to update avatar: $e");
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<String> _saveImageToLocal(File imageFile) async {
    final Directory appDir = await getApplicationDocumentsDirectory();
    final String fileName =
        'avatar_${DateTime.now().millisecondsSinceEpoch}.jpg';
    final String localPath = '${appDir.path}/avatars/$fileName';

    final Directory avatarDir = Directory('${appDir.path}/avatars');
    if (!await avatarDir.exists()) {
      await avatarDir.create(recursive: true);
    }

    final File localFile = await imageFile.copy(localPath);
    return localFile.path;
  }

  void _showEditUsernameDialog() {
    final coordinator = Provider.of<GlobalStateCoordinator>(
      context,
      listen: false,
    );
    final currentUsername = coordinator.currentUser?.userName ?? '';

    AppUtils.showEditUsernameDialog(
      context,
      currentUsername: currentUsername,
      onConfirm: (newUsername) async {
        await _updateUserName(newUsername);
      },
    );
  }

  Future<void> _updateUserName(String newUserName) async {
    if (newUserName.isEmpty) {
      AppUtils.showError(context, "User name cannot be empty");
      return;
    }

    try {
      final coordinator = Provider.of<GlobalStateCoordinator>(
        context,
        listen: false,
      );
      await coordinator.updateUserInfo(newUserName);

      if (mounted) {
        AppUtils.showSuccess(context, "User name updated successfully");
      }
    } catch (e) {
      if (mounted) {
        AppUtils.showError(context, "Failed to update user name: $e");
      }
    }
  }

  void _handleSettingsItemTap(String title) {
    switch (title) {
      case 'Privacy Policy':
        AppUtils.openUrl(
          'https://www.freeprivacypolicy.com/live/3bdfacc3-83cb-4ca6-a9f5-53880c8b1e31',
        );
        break;
      case 'Terms Of service':
        AppUtils.openUrl(
          'https://www.freeprivacypolicy.com/live/d17327ba-4512-48f5-b743-6215587159ec',
        );
        break;
      case 'Delete Account':
        _showDeleteAccountDialog();
        break;
    }
  }

  void _showDeleteAccountDialog() {
    AppUtils.showConfirmDialog(
      context,
      title: 'Delete Account',
      message:
          'Are you sure you want to delete your account? This action cannot be undone.',
      confirmText: 'Delete',
      cancelText: 'Cancel',
      onConfirm: () {
        _performFakeAccountDeletion();
      },
    );
  }

  void _performFakeAccountDeletion() async {
    if (mounted) {
      AppUtils.showSuccess(context, "Account deleted successfully");
    }

    await Future.delayed(const Duration(seconds: 1));

    if (!mounted) return;

    final coordinator = Provider.of<GlobalStateCoordinator>(
      context,
      listen: false,
    );
    coordinator.logout();
    Navigator.of(context).pushNamedAndRemoveUntil('/main', (route) => false);
  }

  void _logout() {
    AppUtils.showConfirmDialog(
      context,
      title: 'Log Out',
      message: 'Are you sure you want to log out?',
      confirmText: 'Log Out',
      cancelText: 'Cancel',
      onConfirm: () {
        final coordinator = Provider.of<GlobalStateCoordinator>(
          context,
          listen: false,
        );
        coordinator.logout();
        AppUtils.showSuccess(context, "Logout successful");
        Navigator.of(
          context,
        ).pushNamedAndRemoveUntil('/main', (route) => false);
      },
    );
  }
}
